<template>
  <el-dialog v-model="visible" title="申请详情" top="0vh" :close-on-click-modal="false" @close="handleClose">
    <div class="detail-content">
      <!-- 申请人基本信息 -->
      <div class="applicant-summary">
        <div class="avatar-section">
          <el-avatar :src="applicantData.avatar" :size="50" />
          <div class="applicant-info">
            <div class="name">{{ applicantData.name }}</div>
            <el-tag :type="getStatusType(applicantData.status)">
              {{ getStatusText(applicantData.status) }}
            </el-tag>
          </div>
        </div>
        <div class="application-date">申请于 {{ formatDate(applicantData.createTime) }}</div>
      </div>

      <!-- 个人信息 -->
      <div class="info-section">
        <div class="section-header">
          <el-icon><User /></el-icon>
          <span>个人信息</span>
        </div>
        <div class="info-grid">
          <div class="info-item">
            <span class="label">姓名:</span>
            <span class="value">{{ applicantData.name }}</span>
          </div>
          <div class="info-item">
            <span class="large-label">身份证号:</span>
            <span class="value">
              <el-tooltip
                :content="getTooltipContent()"
                placement="top"
                :disabled="!showIdCardTooltip"
                :show-after="300"
                :hide-after="100"
              >
                <span class="id-card-hover" @mouseenter="handleIdCardMouseEnter" @mouseleave="handleIdCardMouseLeave">
                  {{ applicantData.idCard }}
                </span>
              </el-tooltip>
            </span>
          </div>
          <div class="info-item">
            <span class="short-label">性别:</span>
            <span class="value">{{ applicantData.gender }}</span>
          </div>
          <div class="info-item">
            <span class="large-label">出生日期:</span>
            <span class="value">{{ applicantData.birthday }}</span>
          </div>
          <div class="info-item">
            <span class="short-label">年龄:</span>
            <span class="value">{{ applicantData.age }}岁</span>
          </div>
        </div>
      </div>

      <!-- 资格认证信息 -->
      <div class="info-section">
        <div class="section-header">
          <el-icon><Document /></el-icon>
          <span>资格认证信息</span>
        </div>
        <div class="certificate-section">
          <div class="certificate-label">证书图片</div>
          <div class="certificate-images">
            <div v-for="(image, index) in certificateImages" :key="index" class="certificate-image-item">
              <el-image
                :src="image"
                :alt="`证书图片${index + 1}`"
                class="certificate-image"
                :preview-src-list="certificateImages"
                :initial-index="index"
                fit="cover"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 身份证照片 -->
      <div class="info-section">
        <div class="section-header">
          <el-icon><Picture /></el-icon>
          <span>身份证照片</span>
        </div>
        <div class="id-photos">
          <div class="id-photo-item">
            <div class="photo-label">身份证正面</div>
            <div class="photo-container">
              <el-image
                v-if="applicantData.idCardFront"
                :src="applicantData.idCardFront"
                alt="身份证正面"
                class="id-photo"
                :preview-src-list="[applicantData.idCardFront]"
                fit="cover"
              />
              <div v-else class="no-image">暂无图片</div>
            </div>
          </div>
          <div class="id-photo-item">
            <div class="photo-label">身份证背面</div>
            <div class="photo-container">
              <el-image
                v-if="applicantData.idCardBack"
                :src="applicantData.idCardBack"
                alt="身份证背面"
                class="id-photo"
                :preview-src-list="[applicantData.idCardBack]"
                fit="cover"
              />
              <div v-else class="no-image">暂无图片</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 审核信息 - 仅审核后显示 -->
      <div v-if="isAudited" class="info-section">
        <div class="section-header">
          <el-icon><Check /></el-icon>
          <span>审核信息</span>
        </div>
        <div class="audit-info">
          <div class="audit-item">
            <span class="label">审核人:</span>
            <span class="value">{{ applicantData.checkUser || 'admin' }}</span>
          </div>
          <div class="audit-item">
            <span class="label">审核时间:</span>
            <span class="value">{{ formatDate(applicantData.checkTime) }}</span>
          </div>

          <!-- 审核意见 - 仅在有内容时显示 -->
          <div v-if="applicantData.checkOpinion" class="audit-item opinion">
            <span class="label">审核意见:</span>
            <div class="opinion-content">{{ applicantData.checkOpinion }}</div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { getAuthenticationDetail, getIdCard } from '@/api/autentication';
import type { AuthenticationResponse } from '@/api/model/authenticationModel';
import { Check, Document, Picture, User } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { computed, ref, watch } from 'vue';

// 组件属性
interface Props {
  visible: boolean;
  data: AuthenticationResponse | null;
}

// 组件事件
interface Emits {
  (e: 'update:visible', value: boolean): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

// 申请人数据 - 现在从API获取
const applicantData = ref<AuthenticationResponse>({} as AuthenticationResponse);

// 身份证相关状态
const plainIdCard = ref<string>(''); // 明文身份证号
const showIdCardTooltip = ref<boolean>(false); // 是否显示身份证提示框
const idCardLoading = ref<boolean>(false); // 身份证加载状态
const lastRequestTime = ref<number>(0); // 上次请求时间
const THROTTLE_DELAY = 2000; // 节流延迟时间（2秒）

// 获取详情数据
const fetchDetailData = async (id: number) => {
  try {
    const response = await getAuthenticationDetail(id);
    applicantData.value = response.data.data;
  } catch (error: any) {
    console.error('获取认证详情失败:', error);
    ElMessage.error(error.message || '获取详情失败');
  }
};

// 监听弹窗显示状态和传入的数据
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible && props.data) {
      // 弹窗打开时，直接使用父组件传入的数据
      applicantData.value = props.data;
      // 重置身份证相关状态，确保每次都能重新获取
      plainIdCard.value = '';
      showIdCardTooltip.value = false;
      idCardLoading.value = false;
      lastRequestTime.value = 0; // 重置节流时间
    }
  },
  { immediate: true },
);

// 证书图片数组
const certificateImages = computed(() => {
  return applicantData.value.certificatePhotos || [];
});

// 是否已审核
const isAudited = computed(() => {
  return applicantData.value.status !== 0; // 0表示待审核
});

// 状态相关方法
const getStatusText = (status: number) => {
  const statusMap = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝',
    3: '需要补充材料',
    4: '审核中',
  };
  return statusMap[status] || '未知状态';
};

// Element Plus 标签类型映射
const getStatusType = (status: number) => {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'danger',
    3: 'info',
    4: 'primary',
  };
  return typeMap[status] || 'default';
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    })
    .replace(/\//g, '/');
};

// 关闭弹窗
const handleClose = () => {
  visible.value = false;
};

// 获取明文身份证号
const fetchPlainIdCard = async (id: number) => {
  try {
    idCardLoading.value = true;
    const response = await getIdCard(id);
    plainIdCard.value = response.data.data || '';
  } catch (error: any) {
    ElMessage.error(error.message || '获取明文身份证失败');
    plainIdCard.value = '获取失败';
  } finally {
    idCardLoading.value = false;
  }
};

// 鼠标进入身份证区域
const handleIdCardMouseEnter = () => {
  const currentTime = Date.now();

  // 弹窗打开后，鼠标悬浮就立即发送请求获取明文身份证
  if (applicantData.value.id && !idCardLoading.value) {
    // 节流控制：如果距离上次请求时间不足2秒，则不发送新请求
    if (currentTime - lastRequestTime.value >= THROTTLE_DELAY) {
      fetchPlainIdCard(applicantData.value.id);
      lastRequestTime.value = currentTime;
    }
  }
  showIdCardTooltip.value = true;
};

// 鼠标离开身份证区域
const handleIdCardMouseLeave = () => {
  showIdCardTooltip.value = false;
};

// 获取提示框内容
const getTooltipContent = () => {
  if (idCardLoading.value) {
    return '正在获取明文身份证...';
  }
  if (plainIdCard.value) {
    return `完整身份证：${plainIdCard.value}`;
  }
  return '悬浮查看明文身份证';
};
</script>

<style scoped lang="less">
.detail-content {
  padding: 0;

  // 申请人基本信息
  .applicant-summary {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 0;
    border-bottom: 1px solid #e5e7eb;
    margin-bottom: 24px;

    .avatar-section {
      display: flex;
      align-items: center;
      gap: 16px;

      .applicant-info {
        display: flex;
        flex-direction: column;
        gap: 8px;

        .name {
          font-size: 18px;
          font-weight: 600;
          color: #1f2937;
        }
      }
    }

    .application-date {
      font-size: 14px;
      color: #6b7280;
    }
  }

  // 信息区块
  .info-section {
    margin-bottom: 24px;

    .section-header {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 16px;
      font-weight: 600;
      color: #1f2937;
      margin-bottom: 16px;
      padding-bottom: 8px;
      border-bottom: 2px solid #e5e7eb;
    }

    // 个人信息网格
    .info-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 16px;

      .info-item {
        display: flex;
        align-items: center;
        gap: 8px;

        .short-label,
        .label {
          font-size: 14px;
          color: #6b7280;
          min-width: 50px;
        }

        .large-label {
          font-size: 14px;
          color: #6b7280;
          min-width: 80px;
        }

        .value {
          font-size: 14px;
          color: #1f2937;
          font-weight: 500;

          // 身份证悬浮样式
          .id-card-hover {
            cursor: pointer;
            padding: 2px 4px;
            border-radius: 4px;
            transition: all 0.2s ease;
            display: inline-block;

            &:hover {
              background-color: #f0f9ff;
              color: #0052d9;
              border: 1px solid #bfdbfe;
            }
          }
        }
      }
    }

    // 证书图片区域
    .certificate-section {
      .certificate-label {
        font-size: 14px;
        color: #6b7280;
        margin-bottom: 12px;
      }

      .certificate-images {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 16px;

        .certificate-image-item {
          .certificate-image {
            width: 100%;
            height: 150px;
            border-radius: 8px;
            border: 1px solid #e5e7eb;
            cursor: pointer;
            transition: all 0.2s ease;

            &:hover {
              border-color: #0052d9;
              box-shadow: 0 2px 8px rgba(0, 82, 217, 0.15);
            }
          }
        }
      }
    }

    // 身份证照片区域
    .id-photos {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 24px;

      .id-photo-item {
        .photo-label {
          font-size: 14px;
          color: #6b7280;
          margin-bottom: 12px;
        }

        .photo-container {
          .id-photo {
            width: 100%;
            height: 200px;
            border-radius: 8px;
            border: 1px solid #e5e7eb;
            cursor: pointer;
            transition: all 0.2s ease;

            &:hover {
              border-color: #0052d9;
              box-shadow: 0 2px 8px rgba(0, 82, 217, 0.15);
            }
          }

          .no-image {
            width: 100%;
            height: 200px;
            border-radius: 8px;
            border: 1px dashed #d1d5db;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #9ca3af;
            font-size: 14px;
          }
        }
      }
    }

    // 审核信息区域
    .audit-info {
      background-color: #f9fafb;
      padding: 16px;
      border-radius: 8px;
      border-left: 4px solid #10b981;

      .audit-item {
        display: flex;
        align-items: flex-start;
        gap: 8px;
        margin-bottom: 12px;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          font-size: 14px;
          color: #6b7280;
          min-width: 80px;
          flex-shrink: 0;
        }

        .value {
          font-size: 14px;
          color: #1f2937;
          font-weight: 500;
        }

        // 审核意见样式
        &.opinion {
          .opinion-content {
            background-color: #dbeafe;
            padding: 12px;
            border-radius: 6px;
            border-left: 4px solid #3b82f6;
            font-size: 14px;
            color: #1e40af;
            line-height: 1.5;
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .detail-content {
    .info-grid {
      grid-template-columns: 1fr;
    }

    .id-photos {
      grid-template-columns: 1fr;
    }

    .certificate-images {
      grid-template-columns: 1fr;
    }
  }
}
</style>
